//==================商家端======================

const dataKit = require( "./util/dataKit")
const dateKit = require( "./util/dateKit")
const businessService = require( "./util/businessService");
const util = require("./util/util");

/**
 * 登录（保存token）
 */
exports.login = async (context) => {
    const {userNick} = context.data;
    const {accessToken,openId} = context;
    if(!userNick){
        return {code:-1,msg:"userNick是必须的"};
    }
    if(!accessToken){
        return {code:-1,msg:"请使用真机调试",data:"accessToken是必须的"};
    }
    
    let merchant = await businessService.getMerchantByOpenId(context,openId);
    if(!merchant){
        merchant = {
            openId:openId,
            createTime:dateKit.getCurrentDateTime()
        };
    }
    
    merchant.loginTime =  dateKit.getCurrentDateTime();
    merchant.userNick = userNick;
    merchant.accessToken = accessToken;
    const result = await dataKit.insertOrUpdate(context,"merchant_info",merchant);
    return {code:0,msg:"登录成功"};
};


/**
 * 获取完成上传作品人数
 */
exports.getUploadWorkPeopleNum = async (context) => {
  let sys_setting = await dataKit.findOne(context,"sys_setting",{key:"sys_setting"});
  return {code:0,msg:"获取成功",data:sys_setting.uploadWorkPeopleNum};
}

/**
 * 设置完成上传作品人数
 * @param {*} context 
 */
exports.setUploadWorkPeopleNum = async (context) => {
  const {uploadWorkPeopleNum} = context.data;
  if(!uploadWorkPeopleNum){
    return {code:-1,msg:"缺少uploadWorkPeopleNum参数"};
  }
  
  let sys_setting = await dataKit.findOne(context,"sys_setting",{key:"sys_setting"});
  sys_setting.uploadWorkPeopleNum = uploadWorkPeopleNum;
  await dataKit.updateBy_id(context,"sys_setting",sys_setting);
  return {code:0,msg:"修改成功",data:sys_setting.uploadWorkPeopleNum};
}

/**
 * 获取作品列表
 * @param {*} context 
 */
exports.getWorkList = async (context) => {
  let {status,userNick,pageNum,pageSize} = context.data;
  if(!pageNum){
    pageNum=1;
  }
  if(!pageSize){
    pageSize=15;
  }

  let filter = {status};
  if(userNick){
    filter.userNick = {$regex:userNick};
  }
  let page = await dataKit.findPage(context,"work",filter,{createTime:-1},pageNum,pageSize);

  return {code:0,msg:"获取成功",data:page};
}


/**
 * 审核作品
 * @param {*} context 
 */
exports.approve = async (context) => {
  const {openId,userNick} = context;
  const {_id,status,reason} = context.data;
  let check = util.checkParamsNull(context,"_id,status");
  if(check){
    return {code:-1,msg:"缺少status参数"};
  }
  
  let work = await dataKit.findOne(context,"work",{_id});
  work.status = status;
  work.approverOpenId=openId;
  work.approverUserNick=userNick;
  work.approveTime = dateKit.getCurrentDateTime();
  work.reason=reason;
  await dataKit.updateBy_id(context,"work",work);

  return {code:0,msg:"审核成功"};
}


/**
 * 修改票数
 * @param {*} context 
 */
exports.setVoteNum = async (context) => {
  const {openId,userNick} = context;
  const {_id,voteNum} = context.data;
  let check = util.checkParamsNull(context,"_id,voteNum");
  if(check){
    return {code:-1,msg:"缺少status参数"};
  }
  
  let work = await dataKit.findOne(context,"work",{_id});
  work.voteNum = voteNum;
  await dataKit.updateBy_id(context,"work",work);
  
  return {code:0,msg:"票数修改成功",data:voteNum};
}

/**
 * 获取统计数据
 * @param {*} context 
 */
exports.getData = async (context) => {
  let {startDate,endDate} = context.data;
  let check = util.checkParamsNull(context,"startDate,endDate");
  if(check){
    return check;
  }
  
  let list = [];
  let dateList = dateKit.getDateList(startDate,endDate);
  for(let date of dateList){
    let item = {"日期":date};
    list.push(item);
    
    //日期条件
    let createTime = {$gte:date+' 00:00:00',$lte:date+' 23:59:59'};

    //PV 
    item.PV = await dataKit.count(context,"user_data",{type:"login",createTime});
    //UV
    {
      let count = (await dataKit.aggregate(context,"user_data",[ 
        {
        "$project": {
            date: {
                $substr:  [ '$createTime', 0, 10 ]
            },
            openId:"$openId",
            type:"$type"
        }
      },
      { $match: {type:"login",date}}, 
      {$group:{_id:{openId:"$openId"},total:{$sum:1}}},
    ]))[0];
    item.UV = count?count.total:0;
    }

    //各口味投票数量
    let flavorList = await dataKit.find(context,"flavor",{},{sort:{voteNum:-1}});
    item.各口味投票数="";
    for(let flavor of flavorList){
      item.各口味投票数+=flavor.name+" : "+flavor.voteNum + " , "
    }
    //各宣言投票数量
    let declarationList = await dataKit.find(context,"declaration",{},{sort:{voteNum:-1}});
    item.各宣言投票数="";
    for(let declaration of declarationList){
      item.各宣言投票数+=declaration.name+" : "+declaration.voteNum + " , "
    }
    // 选填口味文案人数
    {
      let count = (await dataKit.aggregate(context,"vote_log",[ 
        {
        "$project": {
            date: {
                $substr:  [ '$createTime', 0, 10 ]
            },
            openId:"$openId",
            type:"$type"
        }
      },
      { $match: {type: 1,date}}, 
      {$group:{_id:{openId:"$openId"},total:{$sum:1}}},
    ]))[0];
    item.选填口味文案人数 = count?count.total:0;
    }
    // 瓶身设计上传人数
       {
      let count = (await dataKit.aggregate(context,"vote_log",[ 
        {
        "$project": {
            date: {
                $substr:  [ '$createTime', 0, 10 ]
            },
            openId:"$openId",
            type:"$type"
        }
      },
      { $match: {type: 3,date}}, 
      {$group:{_id:{openId:"$openId"},total:{$sum:1}}},
    ]))[0];
    item.瓶身设计上传人数 = count?count.total:0;
    }
    // 瓶身设计审核通过人数
    {
      let count = (await dataKit.aggregate(context,"work",[ 
        {
        "$project": {
            date: {
                $substr:  [ '$createTime', 0, 10 ]
            },
            openId:"$openId",
            status:"$status"
        }
      },
      { $match: {status:1,date}}, 
      {$group:{_id:{openId:"$openId"},total:{$sum:1}}},
    ]))[0];
    item.瓶身设计审核通过人数 = count?count.total:0;
    }
    // 瓶身设计作品获票数
    
    // 引导关注人数
    item.引导关注人数 = await dataKit.count(context,"game_num_log",{type:"follow",createTime});
    // 引导入会人数
    item.引导入会人数 = await dataKit.count(context,"game_num_log",{type:"joinMember",createTime});
    // 分享人数
    item.分享人数 = await dataKit.count(context,"share_log",{friendId:{$exists:true},createTime});
    // 分享次数
    item.分享次数 = await dataKit.count(context,"share_log",{createTime});
    // 引导观看直播人数
    item.引导观看直播人数 = await dataKit.count(context,"game_num_log",{type:"watchVideo",createTime});
    
    // 抽奖人数
    {
      let count = (await dataKit.aggregate(context,"draw_log",[ 
        {
        "$project": {
            date: {
                $substr:  [ '$createTime', 0, 10 ]
            },
            openId:"$openId"
        }
      },
      { $match: {date}}, 
      {$group:{_id:{openId:"$openId"},total:{$sum:1}}},
    ]))[0];
    item.抽奖人数 = count?count.total:0;
    }
    // 各奖品抽中数量
    {
      item.各奖品抽中数量 = "";
      let list = await dataKit.find(context,"draw_item",{},{sort:{level:1}});
      for(let drawItem of list){
        let count = await dataKit.count(context,'draw_log',{level:drawItem.level});
        item.各奖品抽中数量+= drawItem.name+" : "+count+" , ";
      }
    }

    // 上传作品的用户信息
    // 用户停留时长
    // 用户留存


  }

  return list;
}

